import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';
import '../controller/invite_controller.dart';

class InviteRewardsBottomSheet extends StatefulWidget {
  @override
  _InviteRewardsBottomSheetState createState() => _InviteRewardsBottomSheetState();
}

class _InviteRewardsBottomSheetState extends State<InviteRewardsBottomSheet>
    with TickerProviderStateMixin {
  late AnimationController _glowController;
  late Animation<double> _glowAnimation;
  late AnimationController _slideController;
  late Animation<Offset> _slideAnimation;
  final InviteController inviteController = Get.find<InviteController>();

  @override
  void initState() {
    super.initState();
    
    // 发光动画控制器
    _glowController = AnimationController(
      duration: Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);
    
    _glowAnimation = Tween<double>(
      begin: 0.5,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _glowController,
      curve: Curves.easeInOut,
    ));

    // 滑入动画控制器
    _slideController = AnimationController(
      duration: Duration(milliseconds: 300),
      vsync: this,
    );
    
    _slideAnimation = Tween<Offset>(
      begin: Offset(0, 1),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _slideController,
      curve: Curves.easeOutCubic,
    ));

    // 立即加载邀请码数据，确保首次显示时数据已准备好
    inviteController.loadInviteInfo();
    
    // 启动滑入动画
    _slideController.forward();
  }

  @override
  void dispose() {
    _glowController.dispose();
    _slideController.dispose();
    super.dispose();
  }

  void _hideBottomSheet() {
    _slideController.reverse().then((_) {
      Navigator.of(context).pop();
    });
  }

  void _copyInviteCode() {
    Clipboard.setData(ClipboardData(text: inviteController.userInviteCode.value ?? ""));
    Get.snackbar(
      'Copied!',
      'Invite code copied to clipboard',
      backgroundColor: Color(0xFF4A4A4A),
      colorText: Colors.white,
      duration: Duration(seconds: 2),
    );
  }

  void _shareNow() {
    _shareInviteCode();
  }

  void _shareInviteCode() {
    final inviteCode = inviteController.userInviteCode.value.isNotEmpty
        ? inviteController.userInviteCode.value
        : '';

    if (inviteCode.isEmpty) {
      Get.snackbar(
        'Tips',
        'Please check your network connection and try again.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
        snackPosition: SnackPosition.TOP,
        margin: EdgeInsets.all(16),
        borderRadius: 12,
      );
      return;
    }

    // 使用分享链接或默认格式
    String shareText;
    if (inviteController.shareUrl.value.isNotEmpty) {
      shareText = '''🚀 Start Managing Cloud Mining Contracts with BitPlanera!
💼 Manage your cloud mining contracts remotely — all mining happens on remote servers.
⚡ Sign up and start managing cloud mining contracts instantly, no delays.
🎁 Enter my invite code to unlock a bonus cloud mining plan and boost your earnings!
🔗 Download Link: ${inviteController.shareUrl.value}
🔑 Invitation Code: $inviteCode''';
    } else {
      shareText = '''🚀 Start Managing Cloud Mining Contracts with BitPlanera!
💼 Manage your cloud mining contracts remotely — all mining happens on remote servers.
⚡ Sign up and start managing cloud mining contracts instantly, no delays.
🎁 Enter my invite code to unlock a bonus cloud mining plan and boost your earnings!
🔗 Download Link: `https://Bit-Fury.com`
🔑 Invitation Code: $inviteCode''';
    }

    // 调用系统分享面板
    Share.share(
      shareText,
      subject: 'BitPlanera - ${'invite_code'.tr}：$inviteCode',
    ).then((_) {
      // 分享完成后可以添加统计或其他逻辑
    }).catchError((error) {
      Get.snackbar(
        'Tips',
        'Share failed, please try again.',
        backgroundColor: Colors.red,
        colorText: Colors.white,
        snackPosition: SnackPosition.TOP,
        margin: EdgeInsets.all(16),
        borderRadius: 12,
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    // 确保数据已加载
    if (inviteController.userInviteCode.value.isEmpty) {
      inviteController.loadInviteInfo();
    }
    
    final screenHeight = MediaQuery.of(context).size.height;
    final screenWidth = MediaQuery.of(context).size.width;
    final bottomPadding = MediaQuery.of(context).padding.bottom;
    final topPadding = MediaQuery.of(context).padding.top;
    
    // 更细致的屏幕尺寸判断
    final isVerySmallScreen = screenWidth < 320; // iPhone SE 第一代等
    final isSmallScreen = screenWidth < 375; // iPhone SE 第二代、iPhone 12 mini等
    final isMediumScreen = screenWidth < 414; // iPhone 11 Pro、iPhone 12等
    final isLargeScreen = screenWidth >= 414; // iPhone 11 Pro Max、iPhone 12 Pro Max等
    
    // 根据屏幕大小动态调整参数
    double getResponsiveValue({
      required double verySmall,
      required double small,
      required double medium,
      required double large,
    }) {
      if (isVerySmallScreen) return verySmall;
      if (isSmallScreen) return small;
      if (isMediumScreen) return medium;
      return large;
    }
    
    return GestureDetector(
      onTap: _hideBottomSheet, // 点击背景关闭弹窗
      behavior: HitTestBehavior.opaque, // 确保整个区域都能响应点击
      child: Container(
        color: Colors.transparent,
        child: GestureDetector(
          onTap: () {}, // 阻止点击事件冒泡到背景
          onPanUpdate: (details) {
            // 向下拖拽时的处理 - 使用更敏感的检测
            if (details.delta.dy > 2) {
              // 可以在这里添加视觉反馈
            }
          },
          onPanEnd: (details) {
            // 向下滑动关闭弹窗 - 降低速度阈值
            if (details.velocity.pixelsPerSecond.dy > 50) {
              _hideBottomSheet();
            }
          },
          child: SlideTransition(
            position: _slideAnimation,
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                width: double.infinity,
                constraints: BoxConstraints(
                  maxHeight: screenHeight * 0.9, // 增加最大高度
                  minHeight: screenHeight * 0.4, // 设置最小高度
                ),
                decoration: BoxDecoration(
                  color: Color(0xFF1A1A1A),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(getResponsiveValue(
                      verySmall: 16,
                      small: 18,
                      medium: 20,
                      large: 24,
                    )),
                    topRight: Radius.circular(getResponsiveValue(
                      verySmall: 16,
                      small: 18,
                      medium: 20,
                      large: 24,
                    )),
                  ),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // 拖拽手柄
                    GestureDetector(
                      onPanUpdate: (details) {
                        // 向下拖拽关闭弹窗 - 更敏感的触发
                        if (details.delta.dy > 1) {
                          _hideBottomSheet();
                        }
                      },
                      onPanEnd: (details) {
                        // 根据滑动速度关闭弹窗
                        if (details.velocity.pixelsPerSecond.dy > 50) {
                          _hideBottomSheet();
                        }
                      },
                      child: Container(
                        margin: EdgeInsets.only(top: getResponsiveValue(
                          verySmall: 8,
                          small: 10,
                          medium: 12,
                          large: 16,
                        )),
                        width: getResponsiveValue(
                          verySmall: 32,
                          small: 36,
                          medium: 40,
                          large: 44,
                        ),
                        height: 4,
                        decoration: BoxDecoration(
                          color: Colors.grey[600],
                          borderRadius: BorderRadius.circular(2),
                        ),
                      ),
                    ),
                    
                    Flexible(
                      child: NotificationListener<ScrollNotification>(
                        onNotification: (ScrollNotification notification) {
                          // 当滚动到顶部且继续向下拖拽时，允许关闭弹窗
                          if (notification is ScrollUpdateNotification) {
                            if (notification.metrics.pixels <= 0 && 
                                notification.scrollDelta != null && 
                                notification.scrollDelta! < -3) {
                              _hideBottomSheet();
                              return true;
                            }
                          }
                          // 检测过度滚动（overscroll）
                          if (notification is OverscrollNotification) {
                            if (notification.overscroll < -10) {
                              _hideBottomSheet();
                              return true;
                            }
                          }
                          return false;
                        },
                        child: SingleChildScrollView(
                        physics: AlwaysScrollableScrollPhysics(), // 确保总是可以滚动
                        padding: EdgeInsets.only(
                          left: getResponsiveValue(
                            verySmall: 12,
                            small: 16,
                            medium: 20,
                            large: 24,
                          ),
                          right: getResponsiveValue(
                            verySmall: 12,
                            small: 16,
                            medium: 20,
                            large: 24,
                          ),
                          top: getResponsiveValue(
                            verySmall: 16,
                            small: 20,
                            medium: 24,
                            large: 30,
                          ),
                          bottom: bottomPadding + getResponsiveValue(
                            verySmall: 16,
                            small: 20,
                            medium: 24,
                            large: 30,
                          ),
                        ),
                        child: Column(
                          children: [
                            // 发光图标
                            AnimatedBuilder(
                              animation: _glowAnimation,
                              builder: (context, child) {
                                return Container(
                                  width: getResponsiveValue(
                                    verySmall: 60,
                                    small: 70,
                                    medium: 80,
                                    large: 100,
                                  ),
                                  height: getResponsiveValue(
                                    verySmall: 60,
                                    small: 70,
                                    medium: 80,
                                    large: 100,
                                  ),
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    boxShadow: [
                                      BoxShadow(
                                        color: Color(0xFFE6B450).withOpacity(_glowAnimation.value * 0.6),
                                        blurRadius: getResponsiveValue(
                                          verySmall: 20,
                                          small: 25,
                                          medium: 30,
                                          large: 35,
                                        ),
                                        spreadRadius: getResponsiveValue(
                                          verySmall: 6,
                                          small: 8,
                                          medium: 10,
                                          large: 12,
                                        ),
                                      ),
                                    ],
                                  ),
                                  child: Container(
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Color(0xFFE6B450),
                                      border: Border.all(
                                        color: Color(0xFFE6B450).withOpacity(0.8),
                                        width: 2,
                                      ),
                                    ),
                                    child: Icon(
                                      Icons.group,
                                      size: getResponsiveValue(
                                        verySmall: 28,
                                        small: 32,
                                        medium: 40,
                                        large: 50,
                                      ),
                                      color: Color(0xFF1A1A1A),
                                    ),
                                  ),
                                );
                              },
                            ),
                            
                            SizedBox(height: getResponsiveValue(
                              verySmall: 16,
                              small: 20,
                              medium: 24,
                              large: 30,
                            )),
                            
                            // 标题
                            Text(
                              'INVITE FRIENDS,\nSHARE REWARDS',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: getResponsiveValue(
                                  verySmall: 20,
                                  small: 22,
                                  medium: 26,
                                  large: 28,
                                ),
                                fontWeight: FontWeight.bold,
                                height: 1.2,
                              ),
                            ),
                            
                            SizedBox(height: getResponsiveValue(
                              verySmall: 8,
                              small: 10,
                              medium: 14,
                              large: 16,
                            )),
                            
                            // 副标题
                            Text(
                              'Share your exclusive invite code and\nearn rich rewards together',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: Colors.grey[400],
                                fontSize: getResponsiveValue(
                                  verySmall: 12,
                                  small: 13,
                                  medium: 15,
                                  large: 16,
                                ),
                                height: 1.4,
                              ),
                            ),
                            
                            SizedBox(height: getResponsiveValue(
                              verySmall: 20,
                              small: 24,
                              medium: 32,
                              large: 40,
                            )),
                            
                            // 奖励说明卡片
                            Container(
                              padding: EdgeInsets.all(getResponsiveValue(
                                verySmall: 12,
                                small: 14,
                                medium: 18,
                                large: 20,
                              )),
                              decoration: BoxDecoration(
                                color: Color(0xFF2A2A2A),
                                borderRadius: BorderRadius.circular(getResponsiveValue(
                                  verySmall: 8,
                                  small: 10,
                                  medium: 12,
                                  large: 14,
                                )),
                                border: Border.all(
                                  color: Color(0xFFE6B450).withOpacity(0.3),
                                  width: 1,
                                ),
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'HOW TO EARN REWARDS',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: getResponsiveValue(
                                        verySmall: 14,
                                        small: 15,
                                        medium: 17,
                                        large: 18,
                                      ),
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                  
                                  SizedBox(height: getResponsiveValue(
                                    verySmall: 12,
                                    small: 14,
                                    medium: 18,
                                    large: 20,
                                  )),
                                  
                                  _buildRewardStep(
                                    '1',
                                    'Share App to Friends',
                                    Icons.share,
                                    getResponsiveValue,
                                  ),
                                  
                                  SizedBox(height: getResponsiveValue(
                                    verySmall: 8,
                                    small: 10,
                                    medium: 14,
                                    large: 16,
                                  )),
                                  
                                  _buildRewardStep(
                                    '2',
                                    'Get Rewards When Friends \nWatch Ads or Buy Plans',
                                    Icons.trending_up,
                                    getResponsiveValue,
                                  ),
                                  
                                  SizedBox(height: getResponsiveValue(
                                    verySmall: 8,
                                    small: 10,
                                    medium: 14,
                                    large: 16,
                                  )),
                                  
                                  _buildRewardStep(
                                    '3',
                                    'Get 20% of Friend\'s Earnings',
                                    Icons.person,
                                    getResponsiveValue,
                                  ),
                                ],
                              ),
                            ),
                            
                            SizedBox(height: getResponsiveValue(
                              verySmall: 16,
                              small: 20,
                              medium: 24,
                              large: 30,
                            )),
                            
                            // 邀请码区域
                            Container(
                              padding: EdgeInsets.all(getResponsiveValue(
                                verySmall: 12,
                                small: 14,
                                medium: 18,
                                large: 20,
                              )),
                              decoration: BoxDecoration(
                                color: Color(0xFF2A2A2A),
                                borderRadius: BorderRadius.circular(getResponsiveValue(
                                  verySmall: 8,
                                  small: 10,
                                  medium: 12,
                                  large: 14,
                                )),
                                border: Border.all(
                                  color: Color(0xFFE6B450).withOpacity(0.3),
                                  width: 1,
                                ),
                              ),
                              child: Column(
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text(
                                        'Invite CODE',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: getResponsiveValue(
                                            verySmall: 12,
                                            small: 14,
                                            medium: 15,
                                            large: 16,
                                          ),
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                      GestureDetector(
                                        onTap: _copyInviteCode,
                                        child: Text(
                                          'COPY',
                                          style: TextStyle(
                                            color: Color(0xFFE6B450),
                                            fontSize: getResponsiveValue(
                                              verySmall: 12,
                                              small: 14,
                                              medium: 15,
                                              large: 16,
                                            ),
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  
                                  SizedBox(height: getResponsiveValue(
                                    verySmall: 8,
                                    small: 12,
                                    medium: 14,
                                    large: 16,
                                  )),
                                  
                                  Row(
                                    children: [
                                      Expanded(
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            vertical: getResponsiveValue(
                                              verySmall: 8,
                                              small: 12,
                                              medium: 14,
                                              large: 16,
                                            ),
                                            horizontal: getResponsiveValue(
                                              verySmall: 8,
                                              small: 12,
                                              medium: 14,
                                              large: 16,
                                            ),
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color(0xFF1A1A1A),
                                            borderRadius: BorderRadius.circular(getResponsiveValue(
                                              verySmall: 6,
                                              small: 8,
                                              medium: 8,
                                              large: 8,
                                            )),
                                            border: Border.all(
                                              color: Color(0xFFE6B450).withOpacity(0.3),
                                              width: 1,
                                            ),
                                          ),
                                          child: Obx(() => Text(
                                            inviteController.userInviteCode.value,
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: getResponsiveValue(
                                                verySmall: 16,
                                                small: 18,
                                                medium: 19,
                                                large: 20,
                                              ),
                                              fontWeight: FontWeight.bold,
                                              letterSpacing: 2,
                                            ),
                                          )),
                                        ),
                                      ),
                                      
                                      SizedBox(width: getResponsiveValue(
                                        verySmall: 8,
                                        small: 12,
                                        medium: 14,
                                        large: 16,
                                      )),
                                      
                                      GestureDetector(
                                        onTap: _shareNow,
                                        child: Container(
                                          padding: EdgeInsets.symmetric(
                                            vertical: getResponsiveValue(
                                              verySmall: 8,
                                              small: 12,
                                              medium: 14,
                                              large: 16,
                                            ),
                                            horizontal: getResponsiveValue(
                                              verySmall: 16,
                                              small: 20,
                                              medium: 22,
                                              large: 24,
                                            ),
                                          ),
                                          decoration: BoxDecoration(
                                            color: Color(0xFFE6B450),
                                            borderRadius: BorderRadius.circular(getResponsiveValue(
                                              verySmall: 6,
                                              small: 8,
                                              medium: 8,
                                              large: 8,
                                            )),
                                          ),
                                          child: Text(
                                            'SHARE NOW',
                                            style: TextStyle(
                                              color: Color(0xFF1A1A1A),
                                              fontSize: getResponsiveValue(
                                                verySmall: 12,
                                                small: 14,
                                                medium: 15,
                                                large: 16,
                                              ),
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildRewardStep(String number, String text, IconData icon, double Function({required double verySmall, required double small, required double medium, required double large}) getResponsiveValue) {
    return Row(
      children: [
        Container(
          width: getResponsiveValue(
            verySmall: 20,
            small: 24,
            medium: 26,
            large: 28,
          ),
          height: getResponsiveValue(
            verySmall: 20,
            small: 24,
            medium: 26,
            large: 28,
          ),
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: Color(0xFFE6B450),
          ),
          child: Center(
            child: Text(
              number,
              style: TextStyle(
                color: Color(0xFF1A1A1A),
                fontSize: getResponsiveValue(
                  verySmall: 10,
                  small: 12,
                  medium: 13,
                  large: 14,
                ),
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        
        SizedBox(width: getResponsiveValue(
          verySmall: 8,
          small: 12,
          medium: 14,
          large: 16,
        )),
        
        Expanded(
          child: Text(
            text,
            style: TextStyle(
              color: Colors.white,
              fontSize: getResponsiveValue(
                verySmall: 12,
                small: 14,
                medium: 15,
                large: 16,
              ),
              height: 1.3,
            ),
          ),
        ),
        
        Icon(
          icon,
          color: Color(0xFFE6B450),
          size: getResponsiveValue(
            verySmall: 16,
            small: 20,
            medium: 22,
            large: 24,
          ),
        ),
      ],
    );
  }
}

// 显示底部弹窗的方法
void showInviteRewardsBottomSheet(BuildContext context) {
  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder: (context) => InviteRewardsBottomSheet(),
  );
}